 
package com.zdkj.subway.rca.service.impl;

import cn.hutool.core.collection.CollectionUtil;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.rca.entity.SwCkDistinctPaymentTvm;
import com.zdkj.subway.rca.entity.SwCkDistinctPaymentTvmTmp;
import com.zdkj.subway.rca.mapper.SwCkDistinctPaymentTvmTmpMapper;
import com.zdkj.subway.rca.service.SwCkDistinctPaymentService;
import com.zdkj.subway.rca.service.SwCkDistinctPaymentTvmService;
import com.zdkj.subway.rca.service.SwCkDistinctPaymentTvmTmpService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.ZoneId;
import java.util.*;

/**
 * 多元化支付平台审核-TVM临时表
 *
 * @author stw
 * @date 2020-10-29 10:35:19
 */
@Service
public class SwCkDistinctPaymentTvmTmpServiceImpl extends ServiceImpl<SwCkDistinctPaymentTvmTmpMapper, SwCkDistinctPaymentTvmTmp> implements SwCkDistinctPaymentTvmTmpService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwCkDistinctPaymentTvmTmpServiceImpl.class);
    private String parsePattern = "yyyy-MM-dd";
    @Autowired
    private SwCkDistinctPaymentService swCkDistinctPaymentService;
    @Autowired
    private SwCkDistinctPaymentTvmService swCkDistinctPaymentTvmService;

    @Override
    public Boolean saveBatchWithExcel(final File excelFile) throws Exception {
    	ExcelReaderBuilder excelReaderBuilder = EasyExcel.read(excelFile);
    	List<ReadSheet> sheets = excelReaderBuilder.build().excelExecutor().sheetList();
        
        List<Map<String,String>> lineMap = swCkDistinctPaymentService.selectLineMap();
        List<Map<String,String>> stationMap = swCkDistinctPaymentService.selectStationMap();
        List<SwCkDistinctPaymentTvmTmp> listDb = new ArrayList<>();
        Map<String,SwCkDistinctPaymentTvmTmp> listMapTemp= new HashMap();//存放支付宝数据，用于数据合并使用
        Map<String,Integer> listMapIndexTemp= new HashMap();//存放支付宝数据索引，用于数据合并使用
        
        for(int n = 0; n < sheets.size(); n++) {
        	 //String sheetName = sheets.get(n).getSheetName();
        	if(n==0){//支付宝,默认先放所有的数据
        		List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet(n).headRowNumber(3).doReadSync();
        		if (CollectionUtil.isNotEmpty(listMap)) {
        	           
                    for (int m = 0; m < listMap.size(); m++) {
                        Map<Integer, String> data = listMap.get(m);
                        // 返回每条数据的键值对 表示所在的列 和所在列的值
                        LOGGER.info("读取到数据:{}", JSON.toJSONString(data));


                        SwCkDistinctPaymentTvmTmp tmpObj = new SwCkDistinctPaymentTvmTmp();
                        if(data.get(0)!=null && "合计".equals(data.get(0))){
                            continue;
                        }
                        if(data.get(2)!=null && "合计".equals(data.get(2))){
                            continue;
                        }
                        String tradeDate = data.get(0);
                        if(StringUtils.isNotEmpty(tradeDate) && tradeDate.length()>10){
                            tradeDate = data.get(0).substring(0, 10);
                        }
                        tmpObj.setTradeDateTmp(tradeDate);//交易日期
                        tmpObj.setLineCodeTmp(data.get(1));
                        tmpObj.setStationCodeTmp(data.get(2));
                        

                        tmpObj.setAlipaySaleMoneyTmp(data.get(4));
                        tmpObj.setAlipayInvestMoneyTmp(data.get(6));

                        tmpObj.setWechatSaleMoneyTmp("0.00");
                        tmpObj.setWechatInvestMoneyTmp("0.00");

                        tmpObj.setBankSaleMoneyTmp("0.00");
                        tmpObj.setBankInvestMoneyTmp("0.00");

                        if (StringUtils.isEmpty(tmpObj.getTradeDateTmp())) {
                            continue;
                        }
                        if (!parseDate(tmpObj.getTradeDateTmp())) {
                            continue;
                        }

                        
                        listMapTemp.put(tradeDate+data.get(1)+data.get(2), tmpObj);//线路、站点、日期三者拼接到一起，用于验证
                        listMapIndexTemp.put(tradeDate+data.get(1)+data.get(2),listDb.size());//存放List索引位
                        final SwCkDistinctPaymentTvmTmp obj = ObjectUtils.getDefaultObj(SwCkDistinctPaymentTvmTmp.class);
                        BeanUtils.copyProperties(tmpObj, obj, "deptId", "creatorId", "creatorName");
                        checkErr(obj,lineMap,stationMap);//统一放到微信进行验证
                        listDb.add(obj);

                    }                   

                }
        		
        	}else if(n==1){//微信
        		List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet(n).headRowNumber(3).doReadSync();
        		if (CollectionUtil.isNotEmpty(listMap)) {
        	           
                    //MultipartFileToFile.delteTempFile(excelFile);
                    for (int m = 0; m < listMap.size(); m++) {
                        Map<Integer, String> data = listMap.get(m);
                        // 返回每条数据的键值对 表示所在的列 和所在列的值
                        LOGGER.info("读取到数据:{}", JSON.toJSONString(data));

                        SwCkDistinctPaymentTvmTmp tmpObj = new SwCkDistinctPaymentTvmTmp();
                        if(data.get(0)!=null && "合计".equals(data.get(0))){
                            continue;
                        }
                        if(data.get(2)!=null && "合计".equals(data.get(2))){
                            continue;
                        }
                        String tradeDate = data.get(0);
                        if(StringUtils.isNotEmpty(tradeDate) && tradeDate.length()>10){
                            tradeDate = data.get(0).substring(0, 10);
                        }
                        tmpObj.setTradeDateTmp(tradeDate);//交易日期
                        tmpObj.setLineCodeTmp(data.get(1));
                        tmpObj.setStationCodeTmp(data.get(2));
                        
                        String indexKey = tradeDate+data.get(1)+data.get(2);
                        boolean isNotExist = true;
                        if(listMapTemp!=null && listMapTemp.size()>0){
                        	if(listMapTemp.containsKey(indexKey)){
                        		isNotExist = false;
                        		tmpObj = listMapTemp.get(indexKey);
                        	}
                        	
                        }
                        
                        if(isNotExist){
                        	 tmpObj.setAlipaySaleMoneyTmp("0.00");
                             tmpObj.setAlipayInvestMoneyTmp("0.00");
                             tmpObj.setBankSaleMoneyTmp("0.00");
                             tmpObj.setBankInvestMoneyTmp("0.00");
                        }
                       

                        tmpObj.setWechatSaleMoneyTmp(data.get(4));
                        tmpObj.setWechatInvestMoneyTmp(data.get(6));

                        

                        if (StringUtils.isEmpty(tmpObj.getTradeDateTmp())) {
                            continue;
                        }
                        if (!parseDate(tmpObj.getTradeDateTmp())) {
                            continue;
                        }

                        listMapTemp.put(tradeDate+data.get(1)+data.get(2), tmpObj);//线路、站点、日期三者拼接到一起，用于验证
                        //listMapIndexTemp.put(data.get(0)+data.get(1)+data.get(2),listDb.size());//存放List索引位
                        final SwCkDistinctPaymentTvmTmp obj = ObjectUtils.getDefaultObj(SwCkDistinctPaymentTvmTmp.class);
                        BeanUtils.copyProperties(tmpObj, obj, "deptId", "creatorId", "creatorName");
                        checkErr(obj,lineMap,stationMap);
                        if(isNotExist){
                        	listDb.add(obj);	
                        }else{
                        	listDb.set(listMapIndexTemp.get(indexKey), obj);  //替换指定位置的数据。
                        	
                        }
                        

                    }                   

                }
        		
        	}else {//银行
                List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet(n).headRowNumber(3).doReadSync();
                if (CollectionUtil.isNotEmpty(listMap)) {

                    //MultipartFileToFile.delteTempFile(excelFile);
                    for (int m = 0; m < listMap.size(); m++) {
                        Map<Integer, String> data = listMap.get(m);
                        // 返回每条数据的键值对 表示所在的列 和所在列的值
                        LOGGER.info("读取到数据:{}", JSON.toJSONString(data));

                        SwCkDistinctPaymentTvmTmp tmpObj = new SwCkDistinctPaymentTvmTmp();
                        if(data.get(0)!=null && "合计".equals(data.get(0))){
                            continue;
                        }
                        if(data.get(2)!=null && "合计".equals(data.get(2))){
                            continue;
                        }
                        String tradeDate = data.get(0);
                        if(StringUtils.isNotEmpty(tradeDate) && tradeDate.length()>10){
                            tradeDate = data.get(0).substring(0, 10);
                        }
                        tmpObj.setTradeDateTmp(tradeDate);//交易日期
                        tmpObj.setLineCodeTmp(data.get(1));
                        tmpObj.setStationCodeTmp(data.get(2));

                        String indexKey = tradeDate+data.get(1)+data.get(2);
                        boolean isNotExist = true;
                        if(listMapTemp!=null && listMapTemp.size()>0){
                            if(listMapTemp.containsKey(indexKey)){
                                isNotExist = false;
                                tmpObj = listMapTemp.get(indexKey);
                            }

                        }

                        if(isNotExist){
                            tmpObj.setAlipaySaleMoneyTmp("0.00");
                            tmpObj.setAlipayInvestMoneyTmp("0.00");
                            tmpObj.setWechatSaleMoneyTmp("0.00");
                            tmpObj.setWechatInvestMoneyTmp("0.00");
                        }

                        tmpObj.setBankSaleMoneyTmp(data.get(4));
                        tmpObj.setBankInvestMoneyTmp(data.get(6));


                        if (StringUtils.isEmpty(tmpObj.getTradeDateTmp())) {
                            continue;
                        }
                        if (!parseDate(tmpObj.getTradeDateTmp())) {
                            continue;
                        }

                        final SwCkDistinctPaymentTvmTmp obj = ObjectUtils.getDefaultObj(SwCkDistinctPaymentTvmTmp.class);
                        BeanUtils.copyProperties(tmpObj, obj, "deptId", "creatorId", "creatorName");
                        checkErr(obj,lineMap,stationMap);
                        if(isNotExist){
                            listDb.add(obj);
                        }else{
                            listDb.set(listMapIndexTemp.get(indexKey), obj);  //替换指定位置的数据。

                        }
                    }
                }
            }
           
        } 
        MultipartFileToFile.delteTempFile(excelFile);
        if(!listDb.isEmpty()) {
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("CREATOR_ID", listDb.get(0).getCreatorId());
            this.baseMapper.deleteByMap(columnMap);
            return  this.saveBatch(listDb);
        }

        return false;

       
    }

    private String getLineCode (List<Map<String,String>> lineMap,String lineName) {
        for (Map<String,String> map : lineMap){
            if(lineName.equals(map.get("NAME"))){
                return map.get("CODE");
            }
        }
        return "";
    }
    private String getStationCode (List<Map<String,String>> stationMap,String stationName,String lineCode) {
        for (Map<String,String> map : stationMap){
            if(stationName.equals(map.get("NAME")) && lineCode.equals(map.get("LINE_CODE"))){
                return map.get("CODE");
            }
        }
        return "";
    }


    private void checkErr(SwCkDistinctPaymentTvmTmp obj, List<Map<String,String>> lineMap, List<Map<String,String>> stationMap) {
        //更新字段
        String tradeDateTmp = obj.getTradeDateTmp();
        try {
            Date tradeDate = DateUtils.parseDate(tradeDateTmp, parsePattern);
            obj.setTradeDate(tradeDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
        } catch (Exception e) {
            obj.setErrMsg("交易日期 为空或格式错误");
        }

        if(StringUtils.isNotEmpty(obj.getLineCodeTmp())){
            String lineCode = getLineCode(lineMap,obj.getLineCodeTmp());
            if(StringUtils.isNotEmpty(lineCode)){
                obj.setLineCode(lineCode);
            } else {
                obj.setErrMsg("线路名称 为空或不规范");
            }

        } else {
            obj.setErrMsg("线路名称 为空");
        }

        if(StringUtils.isNotEmpty(obj.getStationCodeTmp()) && StringUtils.isNotEmpty(obj.getLineCode())){
            String stationCode = getStationCode(stationMap,obj.getStationCodeTmp(),obj.getLineCode());
            if(StringUtils.isNotEmpty(stationCode)){
                obj.setStationCode(stationCode);
            } else {
                obj.setErrMsg("车站名称 为空或不规范");
            }
        } else {
            obj.setErrMsg("车站名称 为空");
        }

        try {
            BigDecimal num = new BigDecimal("100");

            String alipaySaleMoneyTmp = StringUtils.isEmpty(obj.getAlipaySaleMoneyTmp()) ? "0" : obj.getAlipaySaleMoneyTmp();
            BigDecimal alipaySaleMoney = new BigDecimal(alipaySaleMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            alipaySaleMoney = alipaySaleMoney.multiply(num);
            obj.setAlipaySaleMoney(alipaySaleMoney.longValue());

            String alipayInvestMoneyTmp =  StringUtils.isEmpty(obj.getAlipayInvestMoneyTmp()) ? "0" : obj.getAlipayInvestMoneyTmp();
            BigDecimal alipayInvestMoney = new BigDecimal(alipayInvestMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            alipayInvestMoney = alipayInvestMoney.multiply(num);
            obj.setAlipayInvestMoney(alipayInvestMoney.longValue());

            String wechatSaleMoneyTmp =  StringUtils.isEmpty(obj.getWechatSaleMoneyTmp()) ? "0" : obj.getWechatSaleMoneyTmp();
            BigDecimal wechatSaleMoney = new BigDecimal(wechatSaleMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            wechatSaleMoney = wechatSaleMoney.multiply(num);
            obj.setWechatSaleMoney(wechatSaleMoney.longValue());

            String wechatInvestMoneyTmp =  StringUtils.isEmpty(obj.getWechatInvestMoneyTmp()) ? "0" : obj.getWechatInvestMoneyTmp();
            BigDecimal wechatInvestMoney = new BigDecimal(wechatInvestMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            wechatInvestMoney = wechatInvestMoney.multiply(num);
            obj.setWechatInvestMoney(wechatInvestMoney.longValue());

            String bankSaleMoneyTmp =  StringUtils.isEmpty(obj.getBankSaleMoneyTmp()) ? "0" : obj.getBankSaleMoneyTmp();
            BigDecimal bankSaleMoney = new BigDecimal(bankSaleMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            bankSaleMoney = bankSaleMoney.multiply(num);
            obj.setBankSaleMoney(bankSaleMoney.longValue());

            String bankInvestMoneyTmp = StringUtils.isEmpty(obj.getBankInvestMoneyTmp()) ? "0" : obj.getBankInvestMoneyTmp();
            BigDecimal bankInvestMoney = new BigDecimal(bankInvestMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            bankInvestMoney = bankInvestMoney.multiply(num);
            obj.setBankInvestMoney(bankInvestMoney.longValue());
        } catch (Exception e) {
            obj.setErrMsg("金额 为空或格式错误");
        }

        //判断数据是否存在
        SwCkDistinctPaymentTvm swCkDistinctPaymentTvm = new SwCkDistinctPaymentTvm();
		swCkDistinctPaymentTvm.setLineCode(obj.getLineCode());
        swCkDistinctPaymentTvm.setStationCode(obj.getStationCode());
        swCkDistinctPaymentTvm.setTradeDate(obj.getTradeDate());
        swCkDistinctPaymentTvm.setDelFlag("0");
       
		int count= swCkDistinctPaymentTvmService.count(Wrappers.query(swCkDistinctPaymentTvm));
        if (count > 0 && StringUtils.isEmpty(obj.getErrMsg())) {
            obj.setErrMsg("数据已存在");
        }
		/*
        BeanUtils.copyProperties(obj, swCkDistinctPaymentTvm, "deptId","creatorId","creatorName","createTime");
        List<SwCkDistinctPaymentTvm> list = swCkDistinctPaymentTvmService.list(Wrappers.query(swCkDistinctPaymentTvm));
        if (list != null && !list.isEmpty()) {
            obj.setErrMsg("数据已存在");
        }*/
    }

    private boolean parseDate(String string) {
        boolean convertSuccess = true;
        if (string == null) {
            return false;
        }

        try {
            DateUtils.parseDate(string, parsePattern);
        } catch (ParseException e) {
            convertSuccess = false;
        }
        return convertSuccess;
    }

    @Override
    public void saveBatchWithExcelOk(Integer creatorId) {
        //导入先删除
        this.baseMapper.deleteBatchWithExcelOk(creatorId);
        //导入先删除再添加包括重复的
        this.baseMapper.saveBatchWithExcelOkRepeat(creatorId);
        //this.baseMapper.saveBatchWithExcelOk(creatorId);
        saveBatchWithExcelCancel(creatorId);
    }

    @Override
    public void saveBatchWithExcelCancel(Integer creatorId) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("CREATOR_ID", creatorId);
        this.baseMapper.deleteByMap(columnMap);
    }
}
